<template>
  <el-dialog
    top="30px"
    width="800px"
    title="担保意向函"
    append-to-body
    :close-on-click-modal="false"
    :before-close="beforeClose"
    :visible.sync="visible"
  >
    <div v-loading="loading">
      <div class="text-right mb-2">
        <el-button @click="getData()" icon="el-icon-refresh" :loading="loading">刷新</el-button>
        <el-button @click="handleView" :disabled="!letter.doc_id">查看担保意向函</el-button>
      </div>
      <table class="table table-bordered table-vertical-middle text-center" v-loading="loading">
        <tr>
          <td width="20%" class="td-label">客户名称</td>
          <td colspan="3" class="text-left">{{ related.customer_name }}</td>
        </tr>
        <!-- <tr>
          <td class="td-label">函件编号</td>
          <td colspan="3" class="text-left" :class="tdClass">
            <span v-if="isView">
              {{ orgNameShort }} 〔{{ letter.letter_word_no }}〕 {{ letter.letter_number_no }} 号
            </span>
            <div v-else>
              {{ orgNameShort }}〔
              <el-input
                v-model="editData.letter_word_no"
                style="width: 100px"
                placeholder="字号"
              ></el-input>
              〕第 （
              <el-input
                v-model="editData.letter_number_no"
                style="width: 100px"
                placeholder="第号"
              ></el-input>
              ）号
            </div>
          </td>
        </tr> -->
        <tr>
          <td width="20%" class="td-label">
            <span class="text-danger">*</span>
            建议金额
          </td>
          <td width="35%" :class="tdClass">
            <span v-if="isView">{{ letter.apply_funds || '-' }} 万元</span>
            <el-input
              v-else
              v-model="editData.approved_funds"
              v-input-number="{ min: 0, fixed: 2 }"
              placeholder="建议金额"
            >
              <span slot="append">万元</span>
            </el-input>
          </td>
          <td width="20%" class="td-label">
            <span class="text-danger">*</span>
            贷款期限
          </td>
          <td width="25%" :class="tdClass">
            <span v-if="isView">{{ +letter.load_years || '-' }} 月</span>
            <el-input
              v-else
              v-model="editData.months"
              v-input-number="{ min: 0, fixed: 0 }"
              placeholder="贷款期限"
            >
              <span slot="append">月</span>
            </el-input>
          </td>
        </tr>
        <tr>
          <td class="td-label">
            <span class="text-danger">*</span>
            贷款用途
          </td>
          <td colspan="3" :class="tdClass" class="text-left">
            <span v-if="isView">{{ related.funds_use_dir || '-' }}</span>
            <el-input v-else v-model="editData.funds_use_dir" placeholder="贷款实际用途"></el-input>
          </td>
        </tr>
        <tr>
          <td class="td-label">
            <span class="text-danger">*</span>
            贷款银行
          </td>
          <td :class="tdClass">
            <span v-if="isView">{{ related.bank_name || '-' }}</span>
            <select-banks
              class="w-100"
              v-model="editData.bank_id"
              @select="setPublicName"
              filterable
              v-else
            ></select-banks>
          </td>
          <td class="td-label">
            <span class="text-danger">*</span>
            银行分险比例
          </td>
          <td :class="tdClass">
            <span v-if="isView">{{ related.bank_risk_rate || '-' }}%</span>
            <el-input
              v-else
              placeholder="银行分险比列"
              v-input-number="inputOptions"
              v-model="editData.bank_risk_rate"
              class="form-control-ml"
            >
              <span slot="append">%</span>
            </el-input>
          </td>
        </tr>
        <tr>
          <td class="td-label">
            <span class="text-danger">*</span>
            担保机构
          </td>
          <td>{{ org.orgName }}</td>
          <td class="td-label">
            <span class="text-danger">*</span>
            担保机构分险
          </td>
          <td :class="tdClass">
            <span v-if="isView">{{ related.join_risk_rate || '-' }}%</span>
            <el-input
              placeholder="担保公司分险比例"
              v-else
              v-input-number="inputOptions"
              v-model="editData.join_risk_rate"
            >
              <span slot="append">%</span>
            </el-input>
          </td>
        </tr>
        <tr v-if="isUnion">
          <td class="td-label">
            <span class="text-danger">*</span>
            联保机构
          </td>
          <td :class="tdClass">
            <span v-if="isView">{{ related.gua_service_name || '-' }}</span>
            <select-credit
              clearable
              v-else
              class="form-control-ml"
              v-model="editData.gua_service_id"
              @select="setGuaServiceName"
              placeholder="联保机构"
            ></select-credit>
          </td>
          <td class="td-label">
            <span class="text-danger">*</span>
            联保机构分险
          </td>
          <td :class="tdClass">
            <span v-if="isView">{{ related.join_risk_rate_qx || '-' }}%</span>
            <el-input
              v-else
              placeholder="联保机构分险比列"
              v-input-number="inputOptions"
              v-model="editData.join_risk_rate_qx"
            >
              <span slot="append">%</span>
            </el-input>
          </td>
        </tr>

        <tr>
          <td class="td-label">上年度资产总额</td>
          <td :class="tdClass">
            <span v-if="isView">{{ related.assets_funds || '-' }} 万元</span>
            <el-input
              placeholder="上年度资产总额"
              v-else
              v-input-number="{ min: 0, fixed: 2 }"
              v-model="editData.assets_funds"
            >
              <span slot="append">万元</span>
            </el-input>
          </td>
          <td class="td-label">上年度销售收入</td>
          <td :class="tdClass">
            <span v-if="isView">{{ related.sale_income || '-' }} 万元</span>
            <el-input
              placeholder="上年度销售收入"
              v-else
              v-input-number="{ min: 0, fixed: 2 }"
              v-model="editData.sale_income"
            >
              <span slot="append">万元</span>
            </el-input>
          </td>
        </tr>
        <tr>
          <td class="td-label">从业人数</td>
          <td :class="tdClass">
            <span v-if="isView">{{ related.emp_temp_total || '-' }}</span>
            <el-input
              placeholder="从业人数"
              v-else
              v-input-number="{ min: 0, fixed: 0 }"
              v-model="editData.emp_temp_total"
            >
              <span slot="append">人</span>
            </el-input>
          </td>
          <td class="td-label">
            <span class="text-danger">*</span>
            签章日期
          </td>
          <td :class="tdClass">
            <span v-if="isView">
              {{ letter.sign_date }}
            </span>
            <el-date-picker
              v-else
              class="w-100"
              v-model="letter.sign_date"
              placeholder="选择日期"
              type="date"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </td>
        </tr>
        <tr>
          <td colspan="4">
            <small class="text-warning">
              担保意向函由第三方公证公司生成(大约10s延迟)，保存后点击右上角刷新查看文件
            </small>
          </td>
        </tr>
      </table>

      <div class="text-center py-4" v-if="!isView">
        <el-button
          type="primary"
          class="btn-long"
          :loading="submitLoading"
          @click="submit(0)"
          :disabled="+letter.sign_status > 0"
        >
          暂存
        </el-button>
        <el-button
          type="primary"
          class="btn-long"
          :loading="submitLoading"
          @click="submit(1)"
          :disabled="+letter.sign_status > 0"
        >
          盖章
        </el-button>
      </div>

      <div class="text-center py-4" v-if="!viewMode && +letter.sign_status > 0">
        <el-button type="primary" class="btn-long" :loading="submitLoading" @click="reRecord">
          重开担保意向函
        </el-button>
      </div>

      <el-dialog
        top="30px"
        width="900px"
        append-to-body
        :close-on-click-modal="false"
        :before-close="CloseView"
        :visible.sync="letterView"
      >
        <pdf-view :contract-id="contractId" :view-mode="true"></pdf-view>
      </el-dialog>
    </div>
  </el-dialog>
</template>

<script>
import SelectBanks from '@/bigcredit/views/program/components/SelectOrgBank'
import SelectCredit from '@/bigcredit/views/program/components/SelectCredit'
import { nzhToMoney, sub, add } from '@vimi/utils-tool'
import { mapGetters } from 'vuex'
import PdfView from '@/credit/views/county/unionProvince/components/PdfView'
export default {
  components: {
    SelectCredit,
    SelectBanks,
    PdfView,
  },
  props: {
    visible: Boolean,
    viewMode: {
      type: Boolean,
      default: false,
    },
    queryId: String,
  },
  data() {
    return {
      inputOptions: {
        min: 0,
        max: 100,
        fixed: 2,
        onMin: () => this.$message.error('不能小于0'),
        onMax: () => this.$message.error('不能超过100'),
        onFixed: () => this.$message.error('小数点不能超过2位数'),
      },
      loading: false,
      tableName: 'ele_letter_info',
      letter: {},
      letterView: false,
      submitLoading: false,
      editData: {},
      contractId: '',
      related: {},
    }
  },

  created() {},
  computed: {
    ...mapGetters(['org', 'clientId', 'user']),
    orgNameShort() {
      return this.org.orgNameShort
    },
    isView() {
      return this.viewMode || +this.letter.sign_status > 0
    },
    tdClass() {
      return this.isView ? '' : 'input-td'
    },
    isUnion() {
      return +this.related.gua_type === 4
    },
    isNeq100() {
      if (+this.editData.bank_risk_rate && +this.editData.join_risk_rate) {
        return (
          add(
            this.editData.bank_risk_rate,
            this.editData.join_risk_rate,
            this.editData.join_risk_rate_qx
          ) !== 100
        )
      }
      return false
    },
    letterId() {
      return this.letter.ele_letter_info_id
    },
  },
  watch: {
    // related: {
    //   handler: function () {
    //     this.editData = {
    //       ...this.related,
    //       approved_funds: +this.related.approved_funds || this.related.apply_funds,
    //       months: +this.related.months || +this.related.load_years * 12 || '',
    //     }
    //   },
    //   immediate: true,
    //   deep: true,
    // },
    queryId: {
      handler: function () {
        this.getData()
      },
      immediate: true,
    },
  },
  methods: {
    reRecord() {
      this.$prompt('请输入重开理由', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: value => (!value ? '请输入重做原因' : true),
      })
        .then(({ value }) => {
          this.submitLoading = true
          this.$api
            .addData('credit', 're_sign_record', {
              sign_no: this.letter.sign_no,
              doc_id: this.letter.doc_id,
              related_id: this.letterId,
              sign_no_type: 4,
              re_sign_des: value,
              re_sign_person: this.user.realName,
              re_sign_time: this.$utils.dateFormat(new Date()),
              customer_related_id: this.queryId,
              is_re_sign_dir: 1,
            })
            .then(() => {
              this.getData()
              this.$message.success('提交成功！')
              this.handleSuccess()
            })
            .catch(() => this.$message.error(`操作失败，请重试！`))
            .finally(() => {
              this.submitLoading = false
            })
        })
        .catch(() => {})
    },
    setGuaServiceName(service) {
      this.editData.gua_service_name = service?.agency_name ?? ''
    },
    setPublicName(bank) {
      this.editData.bank_type = bank.agency_type_sub || ''
      this.editData.bank_name = bank.agency_name || ''
    },
    validator() {
      const tipMessage = {
        approved_funds: '请输入建议金额',
        months: '请输入贷款期限',
        funds_use_dir: '请输入贷款实际用途',
        bank_id: '请选择贷款银行',
        bank_risk_rate: '请输入银行分险比列',
        join_risk_rate: '请输入担保机构分险比例',
      }
      if (this.isUnion) {
        tipMessage.gua_service_id = '请选择联保机构'
        tipMessage.join_risk_rate_qx = '请输入联保机构分险比列'
      }
      for (let key of Object.keys(tipMessage)) {
        if (!this.editData[key]) {
          return tipMessage[key]
        }
      }
      if (this.isNeq100) {
        return '银行分险比例+担保公司分险比例不等于100%'
      }

      return ''
    },
    submit(type) {
      const inputErr = this.validator()
      if (inputErr) {
        return this.$message.warning(inputErr)
      }
      this.submitLoading = true
      this.$api
        .updateData(this.$serviceName, 'customer_related', this.queryId, {
          bank_id: this.editData.bank_id || '',
          bank_name: this.editData.bank_name,
          bank_type: this.editData.bank_type,
          months: this.editData.months,
          assets_funds: this.editData.assets_funds,
          sale_income: this.editData.sale_income,
          emp_temp_total: this.editData.emp_temp_total,
          approved_funds: this.editData.approved_funds,
          funds_use_dir: this.editData.funds_use_dir,
          gua_type: this.related.gua_type,
          service_id: this.related.service_id,
          recommend_service: this.related.recommend_service,
          join_risk_rate: this.editData.join_risk_rate,
          join_risk_rate_qx: this.isUnion ? this.editData.join_risk_rate_qx : 0,
          bank_risk_rate: this.editData.bank_risk_rate,
          gua_service_id: this.editData.gua_service_id,
          gua_service_name: this.editData.gua_service_name,
        })
        .then(() => {
          this.sendLetter(type)
        })
        .then(() => {
          this.getData()
          this.$message.success('保存成功！')
          this.handleSuccess()
        })
        .catch(err => {
          this.$message.error(err?.data?.error_description || `操作失败，请重试！`)
        })
        .finally(() => {
          this.submitLoading = false
        })
    },
    sendLetter(type) {
      const data = {
        gua_org_id: this.clientId,
        ele_letter_type: 1,
        customer_related_id: this.queryId,
        bear_rate: sub(100, this.editData.bank_risk_rate),
        sign_date: this.$utils.dateFormat(new Date(), 'yyyy年MM月dd日'),
        bank_name: this.editData.bank_name,
        customer_name: this.related.customer_name,
        apply_funds: this.editData.approved_funds,
        apply_funds_capital: nzhToMoney(this.editData.approved_funds * 10000),
        load_years: this.editData.months,
        funds_use_dir: this.editData.funds_use_dir,
        submit_person_name: this.user.realName,
        sign_status: type,
      }
      if (!this.letterId) {
        return this.$api.addData(this.$serviceName, 'ele_letter_info', data)
      } else {
        return this.$api.updateData(this.$serviceName, 'ele_letter_info', this.letterId, data)
      }
    },
    CloseView() {
      this.letterView = false
      this.contractId = ''
    },
    handleView() {
      this.letterView = true
      this.contractId = this.letter.doc_id
    },
    getData() {
      if (!this.queryId) {
        return
      }
      this.loading = true
      Promise.all([
        this.$api.getData(
          this.$serviceName,
          'customer_related',
          {
            'customer_related_id.eq': this.queryId,
          },
          { create_time: 'desc' }
        ),
        this.$api.getData(
          this.$serviceName,
          this.tableName,
          {
            'customer_related_id.eq': this.queryId,
            'ele_letter_type.eq': 1,
          },
          { create_time: 'desc' }
        ),
      ])
        .then(([related, res]) => {
          this.related = related?.data?.[0] ?? {}
          this.editData = {
            ...this.related,
            approved_funds: +this.related.approved_funds || this.related.apply_funds,
            months: +this.related.months || +this.related.load_years * 12 || '',
          }
          this.letter = res?.data?.[0] ?? {
            sign_date: this.$utils.dateFormat(new Date(), 'yyyy-MM-dd'),
          }
          this.$emit('getRelated', this.related)
          this.$emit('getDocId', this.letter?.doc_id)
          this.letter.sign_date = `${this.letter.sign_date.substring(
            0,
            4
          )}-${this.letter.sign_date.substring(5, 7)}-${this.letter.sign_date.substring(8, 10)}`
        })
        .catch(() => {
          this.submitLoading = true
        })
        .finally(() => {
          this.loading = false
        })
    },
    beforeClose() {
      this.$emit('update:visible', false)
    },
    handleSuccess() {
      this.$emit('success', true)
    },
  },
}
</script>
<style lang="scss" scoped></style>
